package com.taobao.schedule.monitor;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.taobao.schedule.checker.Checker;
import com.taobao.schedule.utils.TextUtil;

/**
 * schedule管理中心
 * @author Livis
 *
 */
public class ScheduleMonitor {
	
	private static Logger log = Logger.getLogger(ScheduleMonitor.class);
	
	public static String testShell ="uptime";
	
	private Set<Checker> checkers;
	
	private Map<String,Thread> checkerThreads;
	
	public void init(){
		this.checkerThreads = new HashMap<String, Thread>(this.checkers.size());
		for (Checker c : checkers) {
			final Checker checker = c;
			final String checkerIndex = "checker-"+System.currentTimeMillis();
			this.checkerThreads.put(checkerIndex, new Thread(new Runnable() {
				public void run() {
					while (true) {
						try {
							checker.check();
						} catch (Throwable e) {
							log.warn(checkerIndex + "’s run method failed", e);
						}
						try {
							Thread.sleep(checker.getCheckInterval());
						} catch (InterruptedException e){
							Thread.currentThread().interrupt();
						}
					}
				}
			}, "CheckerThread-" + checkerIndex));
		}
	}
	
	public void run(){
		for(Map.Entry<String, Thread> e : checkerThreads.entrySet()){
			e.getValue().start();
		}
	}
	
	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] { "spring-schedule-monitor.xml" });
//		ScheduleMonitor sm = (ScheduleMonitor) ctx.getBean("scheduleMonitor");
//		if(args[0]!=null){
//			testShell = args[0];
//			System.out.println("testShell"+testShell);
//		}
//		sm.run();
//		log.warn("schedule monitor start......");
		AlertMsgManager a = (AlertMsgManager) ctx.getBean("alertMsgManager");
		a.alertByWW("铁毅", "hard");
		a.alertByMobile("15268555956", "test");
	}

	public Set<Checker> getCheckers() {
		return checkers;
	}

	public void setCheckers(Set<Checker> checkers) {
		this.checkers = checkers;
	}
	
}
